﻿#include "QThreadBase.h"
#include <QDebug>
#include <QDateTime>
#include <QEventLoop>

QThreadBase::QThreadBase()
{
    m_bStopWorkThread = false;
    connect(this, &QThreadBase::sigStartWorkProc, this, &QThreadBase::slotWorkProc);
    moveToThread(&m_thread);
}

QThreadBase::~QThreadBase()
{

}

void QThreadBase::StartWorkThread(int nWaitTime)
{
    m_bStopWorkThread = false;
    m_thread.start();
    if(0 == nWaitTime)
    {
        emit sigStartWorkProc();
    }
    else
    {
        QTimer::singleShot(nWaitTime, this, SLOT(slotWorkProc()));
    }
}

void QThreadBase::StopWorkThread()
{
	m_bStopWorkThread = true;
	m_thread.quit();
	if (!m_thread.wait(5000))
	{
		m_thread.terminate();
	}

  
   


    //qDebug() << "StopWorkThread1:" << GetNowTimeString();
    //if (false == m_thread.wait())
    //{
    //    //m_thread.terminate();//此函数会导致程序崩溃 暂时注释
    //}
    qDebug() << "StopWorkThread:" << QDateTime::currentDateTime();
    //qDebug() << "StopWorkThread:" << GetNowTimeString();
}

//线程循环  nWaitTime|下次线程循环到来的时间，单位：毫秒 (暂时未使用)
void QThreadBase::threadCirculate(int nWaitTime)
{
    if (true == m_bStopWorkThread) return;
    QTimer::singleShot(nWaitTime, this, SLOT(slotWorkProc()));
}

//线程休眠,nWaitTime:ms
void QThreadBase::threadSleep(int nWaitTime)
{
    int nWaitTemp = 50;
    for (int i = nWaitTemp; i <= nWaitTime; i+= nWaitTemp)
    {
        if (true == m_bStopWorkThread) return;
        QEventLoop loop;
        QTimer::singleShot(nWaitTemp, &loop, SLOT(quit()));
        loop.exec();
    }
}
